<template>
  <common-list>
    <!-- 头部搜素start -->
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        @submit.native.prevent
        :model="query"
        ref="queryForm"
        v-show="showSearch"
        :inline="true"
        label-width="63px"
      >
        <el-form-item label="权限名称">
          <common-input v-model="query.permissionName" clearable @enter="handleQuery"/>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="query.status">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="正常" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="query.daterange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            align="right"
          ></el-date-picker>
        </el-form-item>
      </el-form>
    </common-search>
    <!-- 头部搜素end -->

    <!-- 按钮start -->
    <el-row slot="tools" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="edit(null)"
          v-hasPermi="['system:permission:add']"
        >新增
        </el-button>
      </el-col>
    </el-row>
    <!-- 按钮end -->

    <!--列表 start-->
    <common-table
      slot="content"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column label="权限名称" align="left" prop="a">
        <template slot-scope="{ row }">{{ row.permissionName }}</template>
      </el-table-column>

      <!-- <el-table-column label="显示顺序" align="left" prop="a">
        <template slot-scope="{row}">{{ row.roleSort }}</template>
      </el-table-column> -->

      <el-table-column label="状态" align="center" prop="a">
        <template slot-scope="{ row }">
          <el-tag type="success" v-if="row.status == 0">正常</el-tag>
          <el-tag type="danger" v-if="row.status == 1">停用</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="left"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>

      <el-table-column label="操作" align="left" width="200">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="edit(scope.row)"
            v-hasPermi="['system:permission:edit']"
            v-if="scope.row.permissionId !== '1'"
          >编辑
          </el-button>
          <el-button
            type="text"
            @click="setUsers(scope.row)"
            v-hasPermi="['system:permission:bindperson']"
          >人员设置
          </el-button>
          <el-button
            type="text"
            @click="handleShake(scope.row, scope.$index)"
            v-hasPermi="['system:permission:changeStatus']"
            v-if="scope.row.permissionId !== '1'"
            :disabled="scope.row.isDisabledForShake"
          >
            <span v-if="scope.row.status == 0">停用</span>
            <span v-if="scope.row.status == 1">启用</span>
          </el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:permission:remove']"
            v-if="scope.row.permissionId !== '1'"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="query.pageNum"
      :limit.sync="query.pageSize"
      @pagination="getList"
    />

    <editDialog ref="editDialog" @refresh="getList"/>

    <!--    <setUsersDialog ref="setUsersDialog" @refresh="getList"></setUsersDialog>-->
    <template v-if="isShowUser">
      <common-choose-user
        ref="chooseUser"
        type="permission"
        @close="close"
      ></common-choose-user>
    </template>
  </common-list>
</template>

<script>
  import editDialog from './components/authAdd'
  import setUsersDialog from './components/userAdd'
  import {
    getAuthList,
    authDelete,
    changeStatus,
    checkBeforeDelete,
    batchAddUserPermission, role_delete,
    checkBeforeDeleteForPerm
  } from '@/api/management/usercenter/user.js'
  import { selectUsersByPermissionIds, selectUsersUnBindPermission } from '@/api/system/user'
  import BaseList from '@/mixins/BaseList'
  import CommonChooseUser from '@/components/CommonChooseUser'

  export default {
    components: { editDialog, setUsersDialog, CommonChooseUser },
    mixins: [BaseList],
    props: {},
    data() {
      return {
        key:'permissionId',
        filterMenu: '', //菜单筛选
        showSearch: true, // 查询部分显示
        total: 1, // 总条数
        loading: false, // table 加载中
        list: [{ a: 1 }], // 数据列
        selectionIds: '', // 列表选中数据id
        single: true, // 非单个禁用
        multiple: true, // 非多个禁用
        query: {
          pageNum: 1,
          pageSize: 10,
          status: null
          // permissionName: '',
        }, // 查询条件
        selectedUsersList: [], //人员设置中已选择人员
        unSelectedUsersList: [],
        isShowUser: false
      }
    },
    watch: {},
    computed: {},
    methods: {
      /**
       * 选择
       */
      handleSelectionChange(selection) {
        this.selectionIds = selection.map((item) => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /**
       * 获取列表
       */
      getList() {
        this.loading = true
        let query = { ...this.query }
        getAuthList(query)
          .then((res) => {
            if (res && res.code === 200) {
              this.list = res.rows.reduce((r, c) => {
                r.push({
                  ...c,
                  isDisabledForShake: false
                })
                return r
              }, [])
              this.total = res.total
            } else {
              this.list = []
              this.total = 0
              this.handleListTips(res)
            }
          })
          .finally(() => (this.loading = false))
      },
      /**
       * 查询
       */
      handleQuery() {
        if (!!this.query.daterange) {
          this.query.beginTime = this.query.daterange[0]
          this.query.endTime = this.query.daterange[1]
        } else {
          this.query.beginTime = ''
          this.query.endTime = ''
        }

        this.query.pageNum = 1
        this.getList()
      },
      /**
       * 重置查询
       */
      resetQuery() {
        this.query = this.$options.data().query
      },

      /**
       * 启用/停用方法
       */
      changeStatus(row) {
        // row.isDisabledForShake = true
        return new Promise((resolve, reject) => {
          let status = row.status == 0 ? 1 : 0
          changeStatus({ permissionId: row.permissionId, status: status })
            .then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage('操作成功')
                this.query.pageNum = 1
                resolve(res)
                this.getList()
              } else {
                this.$GlobalErrorConfirm('操作失败', res.msg)
                reject()
              }
            })
            .catch((err) => {
              this.$GlobalErrorConfirm('操作失败', err.msg)
              reject()
            })
        })
      },

      /**
       * 添加/编辑
       */
      edit(row) {
        this.$refs.editDialog.show(row ? { ...row } : {})
      },
      /**
       * 人员设置
       */
      setUsers(row) {
        this.isShowUser = true
        this.permissionId = row?.permissionId


        this.$nextTick(() => {
          this.$refs.chooseUser.show(row ? { ...row } : {});
        })



        // this.getSelectedUsers(row?.permissionId)
        //
        // this.selectUsersUnBindPermission(row?.permissionId)
      },
      close() {
        this.isShowUser = false
      },
      /**
       * 获取已选人员
       */
      getSelectedUsers(id) {
        selectUsersByPermissionIds({permissionIds: [id]})
          .then((res) => {
            if (res && res.code === 200) {
              this.selectedUsersList = res.data
            } else {
              this.$GlobalErrorConfirm(
                '获取已选人员信息失败',
                res.msg,
                '重新加载'
              ).then(() => {
                this.getSelectedUsers(id)
              })
            }
          })
          .catch((err) => {
            this.$GlobalErrorConfirm(
              '获取已选人员信息失败',
              err.msg,
              '重新加载'
            ).then(() => {
              this.getSelectedUsers(id)
            })
          })
      },
      // submit(val) {
      //   let params = {
      //     permissionId: this.permissionId,
      //     userIds: val
      //   }
      //   batchAddUserPermission(params)
      //     .then((res) => {
      //       if (res && res.code === 200) {
      //         this.$GlobalSuccessMessage('新增成功')
      //         this.$refs.chooseUser.cancel()
      //         this.getList()
      //       } else {
      //         this.$GlobalErrorConfirm('新增失败', res.msg).then()
      //       }
      //     })
      //     .catch((err) => {
      //       this.$GlobalErrorConfirm('新增失败', err.msg).then()
      //     })
      //     .finally(() => (this.$refs.chooseUser.loading = false))
      // },

      selectUsersUnBindPermission(id) {
        selectUsersUnBindPermission({ permissionIds: [id] }).then(res => {
          this.unSelectedUsersList = res.data
        }).catch(err => {

        }).finally(() => {

        })
      },

      // —————————————————————— 通用删除方法 ——————————————————————

      /**
       * 删除
       */
      deleteData(row) {
        const ids=row?.permissionId
        this.$GlobalDeleteConfirm().then(() => {
          authDelete({ ids })
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage('删除成功')
                  this.query.pageNum = 1
                  this.getList()
                } else {
                  this.$GlobalErrorConfirm('删除失败', res.msg)
                }
              })
              .catch((err) => {
                this.$GlobalErrorConfirm('删除失败', err.msg)
              })
        }).catch(()=>{});
      },
      /**
       * 删除前校验
       */
      beforeDeleteForCheck(ids) {
        return new Promise((resolve, reject) => {
          checkBeforeDeleteForPerm({ ids: ids }).then(res => {
            if(res && res.code === 200) {
              resolve(res)
            } else {
              reject(res)
            }
          }).catch(err => {
            reject(err)
          })
        })
      }
    },
    created() {
      this.getList()
    },
    mounted() {
    }
  }
</script>
<style lang="scss" scoped>
  .container {
    .list-box {
      clear: both;
      height: auto;
      overflow: hidden;
      padding: 20px;
    }
  }
</style>
